package com.runen.infinitemovement.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.runen.infinitemovement.R;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.ChallengeAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.StepForEntity;
import com.runen.infinitemovement.model.entity.TodayStepForValueEntity;
import com.runen.infinitemovement.model.entity.UserExchangeStepEntity;
import com.runen.infinitemovement.steputil.StepUtil;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class StepsForActivity extends BaseActivity {
    @BindView(R.id.top_btn_left)
    Button topBtnLeft;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.tv_total_step)
    TextView tvTotalStep;
    @BindView(R.id.tv_for_step)
    TextView topForStep;
    @BindView(R.id.tv_for_value)
    TextView topForValue;
    @BindView(R.id.tv_sure_for)
    TextView tvSureFor;
    @BindView(R.id.tv_go_for)
    TextView tvGoFor;
    @BindView(R.id.tv_progress_value)
    TextView tvProgressValue;
    @BindView(R.id.rl_scusses)
    RelativeLayout rlScusses;
    @BindView(R.id.ll_for)
    LinearLayout llFor;
    @BindView(R.id.tv_step_num)
    TextView tv_step_num;
    @BindView(R.id.tv_mileage)
    TextView tv_mileage;
    private String value;
    private int intentFlag;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_steps_for;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        mHandler.sendEmptyMessage(1);
        topTitle.setText("步数兑换");
        intentFlag = getIntent().getIntExtra("intentFlag", 0);
        initUserExchangeStep();
    }

    private void onUpDataStep() {
        JSONObject object = new JSONObject();
        try {
            object.put("step", steps);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new UserAPI().upDataStep(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                if (response.getCode() != 0) {
                    ToastUtils.showShort(response.getMessage());
                } else {
                    goFor();
//                    initData();
                }
            }
        });
    }

    private void initData() {
        showDialog();
        value = "可兑换<font color='#ED3F37'>%s点</font>任务值";
        new UserAPI().getStep(new BaseResultCallback<TodayStepForValueEntity>() {
            @Override
            public void onResponse(TodayStepForValueEntity response) {
                dismissDialog();
                if (response.code == 0) {
                    if (response.data != null) {
                        topForValue.setVisibility(View.GONE);
                        topForStep.setText(String.valueOf(response.data.stepCount));
                        topForValue.setText(Html.fromHtml(String.format(value, response.data.progressValue)));
                        if (response.data.progressValue == 0) {
                            tvSureFor.setEnabled(false);
                            tvSureFor.setBackground(CommonUtil.getDrawable(R.drawable.bg_fa5438_f63d5b_dp360_alpha));
                        } else {
                            tvSureFor.setEnabled(true);
                            tvSureFor.setBackground(CommonUtil.getDrawable(R.drawable.bg_fa5438_f63d5b_dp360));
                        }

                    }
                } else {
//                    ToastUtils.showShort(response.msg);
                    topForValue.setText(Html.fromHtml(String.format(value, 0)));
                    tvSureFor.setEnabled(false);
                    tvSureFor.setBackground(CommonUtil.getDrawable(R.drawable.bg_fa5438_f63d5b_dp360_alpha));
                    tvSureFor.setText("请先开启您的长征路");
                }
            }
        });
    }

    private void initUserExchangeStep() {
        new ChallengeAPI().userExchangeStep(new BaseResultCallback<UserExchangeStepEntity>() {
            @Override
            public void onResponse(UserExchangeStepEntity response) {
                if (response.code == 0 && response.data != null) {
                    tv_step_num.setText(response.data.cumulativeSteps + "步");
                    tv_mileage.setText(response.data.cumulativeMileage + "km");
                }
            }
        });
    }

    @OnClick({R.id.top_btn_left, R.id.tv_sure_for, R.id.tv_go_for})
    public void onViewClicked(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.top_btn_left:
                intent.putExtra("completionRatePlus", completionRatePlus);
                intent.putExtra("totalCompletionRatePlus", totalCompletionRatePlus);
                setResult(20, intent);
                finish();
                break;
            case R.id.tv_sure_for:
                goFor();
                break;
            case R.id.tv_go_for:
                if (intentFlag == 1) {
//                    Intent intent = new Intent();
                    intent.putExtra("completionRatePlus", completionRatePlus);
                    intent.putExtra("totalCompletionRatePlus", totalCompletionRatePlus);
                    setResult(20, intent);
                }
                finish();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            intent.putExtra("completionRatePlus", completionRatePlus);
            intent.putExtra("totalCompletionRatePlus", totalCompletionRatePlus);
            setResult(20, intent);
            finish();
            return true;
        }
        return false;
    }

    private double completionRatePlus;
    private double totalCompletionRatePlus;

    private void goFor() {
        showDialog();
        new UserAPI().stepFor(new BaseResultCallback<StepForEntity>() {
            @Override
            public void onResponse(StepForEntity response) {
                dismissDialog();
//                if (response.code == 0) {
                totalCompletionRatePlus = response.data.totalCompletionRatePlus;
                initData();
//                    llFor.setVisibility(View.GONE);
//                    rlScusses.setVisibility(View.VISIBLE);
//                    topTitle.setText("兑换成功");
//                    String scsuess = "成功兑换 <font color='#ED3F37'>+%s</font> 点任务值为我的长征路贡献<font color='#ED3F37'>%s</font>";
//                    if (response.data != null) {
//                        tvProgressValue.setText(Html.fromHtml(String.format(scsuess,
//                                response.data.sectionNumberPlus,
//                                CommonUtil.Double2position(response.data.completionRatePlus * 100) + "%")));
//                        completionRatePlus = response.data.completionRatePlus;
//                    }
//                } else {
//                    ToastUtils.showShort(response.msg);
//                    llFor.setVisibility(View.VISIBLE);
//                    rlScusses.setVisibility(View.GONE);
//                }
            }
        });
    }

    private int steps;
    private boolean isUpStep = true;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 1) {
                steps = StepUtil.getTodayStep(StepsForActivity.this);
                tvTotalStep.setText(String.valueOf(steps));
                mHandler.sendEmptyMessageDelayed(1, 3000);
                if (isUpStep) {
                    if (0 != steps) {
                        onUpDataStep();
                        isUpStep = false;
                    }
                }
            }
            return false;
        }
    });

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeMessages(1);
    }
}